﻿using HY.Utility.Enum;
using HYDataCapture.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HY.Utility.Match;
using System.Data;
using HY.Utility.ImportExport;
using HY.Utility.Net;
using System.Text.RegularExpressions;

namespace HYDataCapture.Presenters
{
    public class TaobaoShopAllGoodsCapturePresenter
    {
        private ITaobaoShopAllGoodsCaptureView _View;
        private DataTable _Data;
        private List<string> _UrlList;
        private int _UrlIndex;
        private Enums.CaptureTypeEnum _CaptureType;

        public TaobaoShopAllGoodsCapturePresenter(ITaobaoShopAllGoodsCaptureView view)
        {
            _View = view;
            _View.GoodsTags = EnumAttributeHelper.GetEnumDescription(typeof(Enums.TaobaoGoodsTagEnum)).ToArray();
            _Data = new DataTable();
            _UrlList = new List<string>();
        }

        public string NextUrl { get; private set; }
        public DataTable Data { get { return _Data; } }

        public void Init()
        {
            _CaptureType = Enums.CaptureTypeEnum.ShopAllGoodsCapture;
            _Data.Rows.Clear();
            _Data.Columns.Clear();
        }

        public void ExportExcel(string fileName)
        {
            try
            {
                if (_Data == null)
                {
                    _View.Log = "没有数据可供导出";
                    return;
                }
                _View.Log = "正在导出...";
                using (var helper = new ExcelHelper(fileName))
                {
                    helper.DataTableToExcel(_Data, "导出数据", true);
                }
                _View.Log = "已导出：" + fileName;
            }
            catch (Exception ex)
            {
                _View.Log = "导出出错：" + ex.Message;
            }
        }
        public void ExportExcelWithGoodsImage(string fileName)
        {
            try
            {
                do
                {
                    if (Data == null)
                    {
                        _View.Log = "没有数据可供导出";
                        break;
                    }
                    var tag = Enums.TaobaoGoodsTagEnum.ImageLink.GetEnumDescription();
                    var index = Data.Columns.IndexOf(tag);
                    if (index == -1)
                    {
                        _View.Log = "不存在Tag，无法导出：" + tag;
                        break;
                    }
                    _View.Log = "正在导出...";
                    using (var helper = new ExcelHelper(fileName))
                    {
                        helper.DataTableToExcel(Data, new List<int>(new int[] { index }));
                    }
                    _View.Log = "已导出：" + fileName;
                } while (false);
            }
            catch (Exception ex)
            {
                _View.Log = "导出出错：" + ex.Message;
            }
        }

        private Enums.CaptureStateEnum ShopAllGoodsDataCapture()
        {
            var output = Enums.CaptureStateEnum.NoMatch;
            do
            {
                if (_View.SelectGoodsTags.Length == 0)
                {
                    _View.Log = "未选中任何商品Tag，无法采集";
                    break;
                }
                string html = _View.DataHtml;

                List<Enums.TaobaoGoodsTagEnum> tagList = new List<Enums.TaobaoGoodsTagEnum>();
                foreach (var tag in _View.SelectGoodsTags)
                {
                    tagList.Add(EnumAttributeHelper.GetEnumValueFromDescription<Enums.TaobaoGoodsTagEnum>(tag));
                    if (_Data.Columns.IndexOf(tag) == -1)
                        _Data.Columns.Add(tag, typeof(string));
                }

                HtmlElementMatcher matcher = new HtmlElementMatcher(html);
                matcher.GetNodesAttributeValues((index, items, outerhtml) =>
                {
                    DataRow row = _Data.NewRow();
                    var matcher2 = new HtmlElementMatcher(outerhtml);
                    for (var i = 0; i < tagList.Count; ++i)
                    {
                        string value = "";
                        switch (tagList[i])
                        {
                            case Enums.TaobaoGoodsTagEnum.Id:
                                {
                                    value = matcher2.GetNodeAttributeValue("//dl", "data-id");
                                }
                                break;
                            case Enums.TaobaoGoodsTagEnum.Title:
                                {
                                    value = matcher2.GetNodeAttributeValue("//dt[@class='photo']//a/img", "alt");
                                }
                                break;
                            case Enums.TaobaoGoodsTagEnum.Link:
                                {
                                    value = matcher2.GetNodeAttributeValue("//dd[@class='detail']//a", "href");
                                    if (!value.StartsWith("http:") && !value.StartsWith("https:"))
                                        value = "http:" + value;
                                }
                                break;
                            case Enums.TaobaoGoodsTagEnum.ImageLink:
                                {
                                    value = matcher2.GetNodeAttributeValue("//dt[@class='photo']//a/img", "src");
                                    if (!value.StartsWith("http:") && !value.StartsWith("https:"))
                                        value = "http:" + value;
                                }
                                break;
                            case Enums.TaobaoGoodsTagEnum.Price:
                                {
                                    value = matcher2.GetNodeInnerText("//span[@class='c-price']");
                                }
                                break;
                            case Enums.TaobaoGoodsTagEnum.SaleNum:
                                {
                                    value = matcher2.GetNodeInnerText("//span[@class='sale-num']");
                                }
                                break;
                            case Enums.TaobaoGoodsTagEnum.Comment:
                                {
                                    value = matcher2.GetNodeInnerText("//*[@class='rates']");
                                    var m = System.Text.RegularExpressions.Regex.Match(value, @"\d+");
                                    if (m.Success)
                                        value = m.Value;
                                }
                                break;
                        }
                        row[i] = value;
                    }
                    _Data.Rows.Add(row);
                }, "//dl[contains(@class,'item')]");

                NextUrl = matcher.GetNodeAttributeValue("//a[contains(text(),'下一页')]", "href");
                if (!string.IsNullOrEmpty(NextUrl))
                {
                    if (!NextUrl.StartsWith("http:") && !NextUrl.StartsWith("https:"))
                        NextUrl = "https:" + NextUrl;
                    output = Enums.CaptureStateEnum.Success;
                }
                else
                    output = Enums.CaptureStateEnum.Completed;
            } while (false);
            return output;

        }
        private Enums.CaptureStateEnum SaleNumCapture()
        {
            var output = Enums.CaptureStateEnum.NoMatch;
            do
            {
                string html = _View.DataHtml;

                HtmlElementMatcher matcher = new HtmlElementMatcher(html);
                var text = matcher.GetNodeInnerText("//div[@class='d-titletab']");
                if (!string.IsNullOrEmpty(text))
                {
                    var m = Regex.Match(text, "月销\\d+");
                    if (m.Success)
                    {
                        _Data.Rows[_UrlIndex][Enums.TaobaoGoodsTagEnum.SaleNum.GetEnumDescription()] = m.Value.Replace("月销", "");
                        output = Enums.CaptureStateEnum.Success;
                    }
                    ++_UrlIndex;
                    if (_UrlIndex < _UrlList.Count)
                    {
                        NextUrl = _UrlList[_UrlIndex];
                        _View.Log = $"剩余{_UrlList.Count - _UrlIndex}条数据待采集";
                        _View.CurrentIndex = _UrlIndex;
                    }
                    else
                        output = Enums.CaptureStateEnum.Completed;
                }
            } while (false);
            return output;
        }
        public Enums.CaptureStateEnum DataCapture()
        {
            var output = Enums.CaptureStateEnum.NoMatch;
            switch(_CaptureType)
            {
                case Enums.CaptureTypeEnum.ShopAllGoodsCapture:
                    output = ShopAllGoodsDataCapture();
                    break;
                case Enums.CaptureTypeEnum.TaobaoSaleNumCapture:
                    output = SaleNumCapture();
                    break;
            }
            SetSalesAmount();
            return output;
        }



        public bool InitUpdateSaleNum()
        {
            var output = false;
            do
            {
                if (_Data.Rows.Count == 0)
                {
                    _View.Log = "数据为空";
                    break;
                }
                if(!_Data.Columns.Contains(Enums.TaobaoGoodsTagEnum.Id.GetEnumDescription()))
                {
                    _View.Log = "不存在Tag，无法采集："+Enums.TaobaoGoodsTagEnum.Id.GetEnumDescription();
                    break;
                }
                if (!_Data.Columns.Contains(Enums.TaobaoGoodsTagEnum.Id.GetEnumDescription()))
                {
                    _View.Log = "不存在Tag，无法采集：" + Enums.TaobaoGoodsTagEnum.SaleNum.GetEnumDescription();
                    break;
                }
                _UrlList.Clear();
                foreach (DataRow row in _Data.Rows)
                {
                    var id = row[Enums.TaobaoGoodsTagEnum.Id.GetEnumDescription()].ToString();
                    var url = $"https://h5.m.taobao.com/awp/core/detail.htm?spm=0.0.0.0&id={id}";
                    _UrlList.Add(url);
                }
                _UrlIndex = 0;
                _CaptureType = Enums.CaptureTypeEnum.TaobaoSaleNumCapture;
                NextUrl = _UrlList[_UrlIndex];
                output = true;
            } while (false);
            return output;
        }

        private bool CheckSaleNumPriceTagExists()
        {
            bool output = false;
            do
            {
                if (!_Data.Columns.Contains(Enums.TaobaoGoodsTagEnum.SaleNum.GetEnumDescription()))
                {
                    break;
                }
                if (!_Data.Columns.Contains(Enums.TaobaoGoodsTagEnum.Price.GetEnumDescription()))
                {
                    break;
                }
                output = true;
            } while (false);
            return output;
        }

        private void SetSalesAmount()
        {
            var output = "";
            do
            {
                if (_Data.Columns.Count == 0)
                    break;
                if (!CheckSaleNumPriceTagExists())
                    break;

                var total = 0m;
                var temp = 0m;
                foreach (DataRow row in _Data.Rows)
                {
                    if (!decimal.TryParse(Convert.ToString(row[Enums.TaobaoGoodsTagEnum.SaleNum.GetEnumDescription()]), out temp))
                        continue;
                    var saleNum = temp;
                    if (!decimal.TryParse(Convert.ToString(row[Enums.TaobaoGoodsTagEnum.Price.GetEnumDescription()]), out temp))
                        continue;
                    var price = temp;
                    total += (price * saleNum);
                }
                output = total.ToString();
            } while (false);
            _View.SaleAmount = output;
        }
    }
}
